import javax.swing.*;
import java.awt.*;
import java.util.Random;

//TIP 要<b>运行</b>代码，请按 <shortcut actionId="Run"/> 或
// 点击装订区域中的 <icon src="AllIcons.Actions.Execute"/> 图标。
public class Game2048 extends JPanel {
    Game2048(){
        spawnTile();
        spawnTile();
    }
    private static final int SIZE = 4;
    private final int[][] grid = new int[SIZE][SIZE];
    private final Random random = new Random();
     private void drawTile(Graphics g,int value,int x,int y){
         int p = (int) ((int) Math.log(value)/Math.log(2));
         g.setColor(value == 0 ? Color.LIGHT_GRAY : new Color(255-p*20,240,200));
         g.fillRect(x,y,100,100);
         g.setColor(Color.black);
         g.drawRect(x,y,100,100);
         if (value != 0){
             String text = String.valueOf(value);
             FontMetrics fm = g.getFontMetrics();
             int textX = x + (100-fm.stringWidth(text))/2;
             int textY = y + (100-fm.getHeight())/2 + fm.getAscent();
             g.drawString(text,textX,textY);
         }
    }

    private void spawnTile(){
         int x,y; //位置
        //避免数字生成在同一个位置
        do {
            x = random.nextInt(SIZE);
            y = random.nextInt(SIZE);
        }while(grid[x][y] != 0);
        grid[x][y] = random.nextInt(10) < 5 ? 2 : 4;
    }
    @Override
    protected void paintComponent(Graphics g){
         super.paintComponent(g);
         g.setColor(Color.LIGHT_GRAY);
         g.fillRect(0,0,getWidth(),getHeight());
         for(int i=0; i<SIZE; i++){
             for (int j=0; j<SIZE; j++){
                 drawTile(g,grid[i][j],j*100,i*100);
             }
         }
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame("2048 Game");
        frame.setSize(420,460);
        Game2048 game2048 = new Game2048();
        frame.add(game2048);
        frame.setVisible(true);
    }
}